import { Button, Card, message, Popconfirm, Table, Image, Tooltip } from 'antd';
import { ColumnsType } from 'antd/es/table';
import { TableRowSelection } from 'antd/es/table/interface';
import { useEffect, useState } from 'react';

import noticeService from '@/api/services/setting/noticeService';
import { Iconify } from '@/components/icon';
import TipIconButton from '@/components/icon/tooltip-icon-button';
import { pagination } from '@/utils/pagination';
import { hasPermission } from '@/utils/permission';

import IndexModal from './modal';
import { NoticeType } from './type';

import { ListData, SearchData } from '#/entity';

export default function Notice() {
  console.log('init');
  const [tableData, setTableData] = useState<ListData<NoticeType>>({ data: [], count: 0 });
  const [searchData, setSearchData] = useState<SearchData>({
    page: 1,
    take: 10,
  });
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [selectedRows, setSelectedRows] = useState<NoticeType[]>([]);
  const onSelectChange = (newSelectedRowKeys: React.Key[], selectedRows: NoticeType[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
    setSelectedRows(selectedRows);
  };
  const rowSelection: TableRowSelection<NoticeType> = {
    selectedRowKeys,
    onChange: onSelectChange,
  };
  const [modalProps, setModalProps] = useState({
    show: false,
    title: '',
    formValue: {},
    onOk: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
      setSearchData((prev) => ({
        ...prev,
        page: 1,
      }));
    },
    onCancel: () => {
      setModalProps((prev) => ({ ...prev, show: false }));
    },
  });
  const onEdit = (record: NoticeType) => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '修改公告管理',
      formValue: record,
    }));
  };
  // 获取信息

  useEffect(() => {
    noticeService.list(searchData).then((res) => {
      console.log('res', res);
      setTableData(res);
    });
  }, [searchData]);

  const onCreate = () => {
    setModalProps((prev) => ({
      ...prev,
      show: true,
      title: '新增公告管理',
      formValue: {},
    }));
  };

  const columns: ColumnsType<NoticeType> = [
    {
      title: '图标',
      width: 120,
      dataIndex: 'cover',
      render: (fileId: number) => <div>{fileId ? <Image src={`${fileId}`} width={80} /> : ''}</div>,
    },
    { title: '标题', dataIndex: 'title', key: 'id', width: 200 },

    {
      align: 'right' as const,
      fixed: 'right' as const,
      title: <div style={{ marginRight: 20 }}>操作</div>,
      dataIndex: 'action',
      render: (_: any, record: any) => (
        <div className="flex w-full justify-end text-gray">
          {hasPermission('WINE:SPU_INFO:UPDATE') && (
            <TipIconButton onClick={() => onEdit(record)} tipText="修改">
              <Iconify icon="solar:pen-bold-duotone" size={18} />
            </TipIconButton>
          )}

          {hasPermission('WINE:SPU_INFO:DELETE') && (
            <Popconfirm
              title={operationDeleteTitle()}
              okText="确定"
              cancelText="取消"
              onConfirm={() => {
                onDelete(record);
              }}
              placement="left"
            >
              <TipIconButton tipText="删除">
                <Iconify icon="mingcute:delete-2-fill" size={18} className="text-error" />
              </TipIconButton>
            </Popconfirm>
          )}
        </div>
      ),
    },
  ];
  const operationDeleteTitle = () => {
    return '确定删除吗？';
  };
  const onDelete = (record: any) => {
    noticeService.deleteBatch({ ids: record.id }).then((res) => {
      if (res > 0) {
        message.success('删除成功');
        setSearchData({
          page: 1,
          take: searchData.take,
        });
      }
    });
  };
  // 批量删除
  const onDeleteBatch = () => {
    if (selectedRowKeys.length === 0) {
      message.warning('请至少选择一条记录');
      return;
    }
    const ids = selectedRowKeys.join(','); // 将选中的 ID 拼接成字符串
    noticeService
      .deleteBatch({ ids })
      .then((res) => {
        if (res > 0) {
          message.success('删除成功');
          setSearchData({
            page: 1,
            take: searchData.take,
          });
          setSelectedRows([]); // 清空选中的行数据
          setSelectedRowKeys([]); // 清空选中的行键
        }
      })
      .catch(() => {
        message.error('删除失败');
      });
  };
  return (
    <Card
      title="公告管理"
      extra={
        <div className="flex items-center gap-2">
          <Tooltip title="批量删除">
            <Popconfirm
              title={`确定删除选择的 ${selectedRowKeys
                .map((key) => {
                  const item = tableData.data.find((data) => data.id === key);
                  return item ? item.title : '';
                })
                .filter(Boolean)
                .join('， ')} 公告吗？`}
              okText="确定"
              cancelText="取消"
              onConfirm={onDeleteBatch} // 绑定确认事件
            >
              <Button
                disabled={selectedRowKeys.length === 0} // 没有选中时禁用按钮
                danger
              >
                批量删除
              </Button>
            </Popconfirm>
          </Tooltip>
          <Button
            type="primary"
            onClick={() => {
              onCreate();
            }}
          >
            新增
          </Button>
        </div>
      }
    >
      <Table
        size="small"
        rowKey="id"
        dataSource={tableData?.data}
        columns={columns}
        scroll={{ x: 'max-content' }}
        rowSelection={rowSelection}
        pagination={pagination({
          page: searchData, onPageChange: (page, rows) => {
            setSearchData((prev) => ({
              ...prev,
              page,
              take: rows,
            }));
          }, count: tableData?.count
        })}
      />
      <IndexModal {...modalProps} />
    </Card>
  );
}
